<?php

include_once( '../api/session.php' );

require_once( '../api/Client.class.php' );

include_once( '../library/config.php' );
include_once( APPLICATION.'User.class.php' );
include_once( APPLICATION.'Payment.class.php' );
include_once( APPLICATION.'Paymentrequest.class.php' );

$pname = 'JaPagoJo';

if( isset( $_POST['username'] ) ) {
	$response = Client::login( $_POST['username'], $_POST['password'] );
	if( strtolower( $response['status'] )  == 'ok' ) {
	  $_SESSION['token'] = $response['token'];
	  $c = new Client( $response['token'] );
	  $profile = $c->getProfile();
	  	  
	  $u = User::findByIdUser($profile['data']['id'] );
	  
	  include_once( 'templates/header.tmp.php' );
	  if( !$u ) {
	  	$acctlist = $c->getAccounts();
	  	if( $profile['data']['accounts'] ) {
	  		foreach( $profile['data']['accounts'] as $acct ) {
	  			$accounts[] = $c->getAccountDetail( $acct );
	  		}
	  	}
	  	//print_r( $accounts );
	    include_once( 'templates/complete_data.tmp.php' );
	  }
	  else
	    include_once( 'templates/contacts.tmp.php' );
	}
	else
	  //login failed
	  echo 'FAIL!';
} elseif( !empty( $_SESSION['token'] ) ) {
	if( isset( $_GET['act'] ) && $_GET['act'] == 'logout' ) {
	  unset( $_SESSION['token'] );
	  include_once( 'templates/header.tmp.php' );
	  include_once( 'templates/login.tmp.php' );
	} else {
		
		
	  if( isset( $_POST['accountchoice'] ) ) {
	    $c = new Client( $_SESSION['token'] );
	    $profile = $c->getProfile();
	    $u = new User( );
	    $u->setId_user( $profile['data']['id'] );
	    $u->setId_account( $_POST['accountchoice'] );
	    $u->insert( '', '', true );
  }
		
		include_once( 'templates/header.tmp.php' );
    $c = new Client( $_SESSION['token'] );
    $profile = $c->getProfile();
        
    $u = User::findByIdUser( $profile['data']['id'] );
    
    include_once( 'templates/header.tmp.php' );
    if( !$u ) {
      $acctlist = $c->getAccounts();
      //print_r( $profile['data']['accounts'] );
      if( $profile['data']['accounts'] ) {
        foreach( $profile['data']['accounts'] as $acct ) {
          $accounts[] = $c->getAccountDetail( $acct );
        }
      }
      //print_r( $accounts );
      include( 'templates/complete_data.tmp.php' );
    }
    else
      include( 'templates/contacts.tmp.php' );
	}
	
} else {
	include_once( 'templates/header.tmp.php' );
  include_once( 'templates/login.tmp.php' );
}

include_once( 'templates/footer.tmp.php' );
  
?>